package org.qydjk.console.service.impl;

import org.qydjk.common.dao.IBaseDao;
import org.qydjk.common.pojo.Category;
import org.qydjk.common.pojo.seller.*;
import org.qydjk.common.service.impl.BaseService;
import org.qydjk.common.shiro.vo.ShiroUser;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.ext.SellerLogEnum;
import org.qydjk.console.service.ISellerService;
import org.qydjk.console.vo.SellerExtendBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * * 商家管理Service
 * Created by Edward_yang on 2017/12/20 0020.
 */
@Service
public class SellerService  extends BaseService implements ISellerService{
    @Autowired
    private IBaseDao baseDao;

    /***
     * 添加
     * @param sellerExtendBean
     * @param shiroUser
     * @param request
     * @return
     * @throws Exception
     */
    public Boolean addSellerALlInfo(SellerExtendBean sellerExtendBean, ShiroUser shiroUser,HttpServletRequest request) throws Exception {
        Boolean flag=false;
        Seller seller=new Seller();
        BeanUtil.copyProperties(sellerExtendBean,seller);
        seller.setAreaIds(StringUtil.dotAddStartEnd(sellerExtendBean.getOneAreaId()+","+sellerExtendBean.getTwoAreaId()+","+sellerExtendBean.getThreeAreaId()));//城市IDs
        seller.setCategoryIds(StringUtil.dotAddStartEnd(seller.getCategoryIds()));//分类IDs\
        seller.setThumbnailImg(seller.getImg());//缩略图
        seller.setCreateTime(new Date());
        seller.setUpdateTime(new Date());
        seller.setProductCount(0);//产品数量 /默认:0
        seller.setInitiatePric(new BigDecimal(0));//默认:0
        seller.setStatus(1);//默认:正常
        seller.setVerifyType(0);//默认:待审核
        List<SellerLabelDetail> slds = new ArrayList<SellerLabelDetail>();
        StringBuffer sbCode = new StringBuffer();
        Enumeration parmNames = request.getParameterNames();
        while (parmNames.hasMoreElements()){
            String para = (String)parmNames.nextElement();
            if(para.startsWith("label_")){
                String labelCode = para.replace("label_","");
                String labelDetailCode = request.getParameter(para);
                SellerLabelDetail sld = new SellerLabelDetail();
                sld.setSellerProductLabelCode(labelCode);
                sld.setSellerProductLabelDetailCode(labelDetailCode);
                sbCode.append(labelDetailCode).append(",");
                slds.add(sld);
            }
        }
        seller.setLabelCodes(StringUtil.dotAddStartEnd(sbCode.toString()));//codeIDs
        Integer sellerID= (Integer) baseDao.save(seller);
        if(sellerID==null){
            return flag;
        }
        System.out.println("商家ID:"+sellerID);
        //保存中间表数据
        Boolean ss= saveSellerCentreEntity(sellerExtendBean,sellerID,slds);
        if(!ss){
            return flag;
        }
        //日志
        SellerLog sellerLog=new SellerLog();
        sellerLog.setSellerId(sellerID);//商家id
        sellerLog.setUserId(shiroUser.getId()); //管理员id
        sellerLog.setUsername(shiroUser.getName());//管理员名称
        sellerLog.setType(SellerLogEnum.ADD.getType()); //状态:增加
        sellerLog.setTypeName(SellerLogEnum.ADD.getTypeName());//名称
        sellerLog.setCreateTime(new Date());
        sellerLog.setUpdateTime(new Date());
        Integer sellerLogId = (Integer) baseDao.save(sellerLog);
        if(sellerLogId!=null){
            flag=true;
        }
        return flag;
    }

    /***
     * 修改
     * @param sellerExtendBean
     * @param shiroUser
     * @param request
     * @return
     * @throws Exception
     */
    public Boolean updateSellerALlInfo(SellerExtendBean sellerExtendBean, ShiroUser shiroUser, HttpServletRequest request) throws Exception {
            Boolean flag=false;
            Seller  seller = baseDao.get(Seller.class,sellerExtendBean.getId());
            BeanUtil.copyProperties(sellerExtendBean,seller);
            seller.setThumbnailImg(seller.getImg());//缩略图
        seller.setAreaIds(StringUtil.dotAddStartEnd(sellerExtendBean.getOneAreaId()+","+sellerExtendBean.getTwoAreaId()+","+sellerExtendBean.getThreeAreaId()));//城市IDs
            seller.setCategoryIds(StringUtil.dotAddStartEnd(seller.getCategoryIds()));//分类IDs
            seller.setUpdateTime(new Date());//修改时间
             List<SellerLabelDetail> slds = new ArrayList<SellerLabelDetail>();
             StringBuffer sbCode = new StringBuffer();
              Enumeration parmNames = request.getParameterNames();
             while (parmNames.hasMoreElements()){
                  String para = (String)parmNames.nextElement();
             if(para.startsWith("label_")){
                String labelCode = para.replace("label_","");
                String labelDetailCode = request.getParameter(para);
                SellerLabelDetail sld = new SellerLabelDetail();
                sld.setSellerProductLabelCode(labelCode);
                sld.setSellerProductLabelDetailCode(labelDetailCode);
                sbCode.append(labelDetailCode).append(",");
                slds.add(sld);
            }
        }
             seller.setLabelCodes(StringUtil.dotAddStartEnd(sbCode.toString()));//codeIDs
            baseDao.update(seller);
            //先执行删除中间表
            baseDao.excuteSQL("DELETE FROM qy_seller_category WHERE seller_id ="+seller.getId());//分类
            baseDao.excuteSQL("DELETE FROM qy_seller_label_detail WHERE seller_id ="+seller.getId());//标签
            baseDao.excuteSQL("DELETE FROM qy_seller_city WHERE seller_id ="+seller.getId());//城市
            baseDao.excuteSQL("DELETE FROM qy_seller_imgs WHERE seller_id ="+seller.getId());//图片
             //保存中间表数据
              Boolean ss= saveSellerCentreEntity(sellerExtendBean,sellerExtendBean.getId(),slds);
                 if(!ss){
                    return flag;
                 }
            //日志
            SellerLog sellerLog=new SellerLog();
            sellerLog.setSellerId(seller.getId());//商家id
            sellerLog.setUserId(shiroUser.getId()); //管理员id
            sellerLog.setUsername(shiroUser.getName());//管理员名称
            sellerLog.setType(SellerLogEnum.UPDATE.getType()); //状态:修改
            sellerLog.setTypeName(SellerLogEnum.UPDATE.getTypeName());//名称
            sellerLog.setCreateTime(new Date());
            sellerLog.setUpdateTime(new Date());
           Integer sellerLogId= (Integer) baseDao.save(sellerLog);
        if(sellerLogId!=null){
            flag=true;
        }
        return flag;
    }


    /***
     *  添加商家城市中间表判断
     * @author Edward_yang
     * @uptime 2017-12-19
     * @param SellercityId 城市ID
     * @param SellerId 商家ID
     * @param level  等级 1,2,3
     * @return Boolean
     */
    public Boolean sveaSellerCity(Integer SellercityId,Integer SellerId,Integer level){
        Boolean flag=false;
        try {
            SellerCity sellerCity=new SellerCity();
            sellerCity.setAreaId(SellercityId);
            sellerCity.setSellerId(SellerId);
            sellerCity.setLevel(level);
            sellerCity.setCreateTime(new Date());
            sellerCity.setUpdateTime(new Date());
         Integer sellerCityID= (Integer) baseDao.save(sellerCity);
         if(sellerCityID!=null){
             flag=true;
         }
            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return flag;
        }
    }

    /***
     * 保存商家关联中间表
     * @author Edward_yang
     * @uptime 2017-12-22
     * @param sellerExtendBean
     * @param sellerID
     * @param slds
     * @return
     * @throws Exception
     */
    public Boolean saveSellerCentreEntity(SellerExtendBean sellerExtendBean,Integer sellerID,  List<SellerLabelDetail> slds)throws  Exception{
        Boolean flag=false;
        //分类中间表
        String CategoryIdsString=sellerExtendBean.getCategoryIds();
        List<Category> CategoryIdsList=baseDao.findBeanBySQL(" select *from qy_category where id in( "+CategoryIdsString+")",Category.class);
        for(Category category:CategoryIdsList ){
            SellerCategory sellerCategory=new SellerCategory();
            sellerCategory.setCategoryId(category.getId());
            sellerCategory.setSellerId(sellerID);
            sellerCategory.setLevel(category.getLevel());//等级
            sellerCategory.setCreateTime(new Date());
            sellerCategory.setUpdateTime(new Date());
            baseDao.save(sellerCategory);
        }
        //标签中间表
        for(SellerLabelDetail spld :slds){
            SellerLabelDetail sellerLabelDetail=new SellerLabelDetail();
            sellerLabelDetail.setSellerProductLabelCode(spld.getSellerProductLabelCode());//标签code
            sellerLabelDetail.setSellerProductLabelDetailCode(spld.getSellerProductLabelDetailCode());//标签明细code
            sellerLabelDetail.setSellerId(sellerID);
            sellerLabelDetail.setCreateTime(new Date() );
            sellerLabelDetail.setUpdateTime(new Date());
            baseDao.save(sellerLabelDetail);
        }
        //城市中间表
        boolean isSend= sveaSellerCity(sellerExtendBean.getOneAreaId(),sellerID,1);
        if(!isSend){return false;}
        isSend=  sveaSellerCity(sellerExtendBean.getTwoAreaId(),sellerID,2);
        if(!isSend){return false;}
        if(sellerExtendBean.getThreeAreaId()!=null){
            isSend= sveaSellerCity(sellerExtendBean.getThreeAreaId(),sellerID,3);
            if(!isSend){return false;}
        }
        //图片中间表
        String ImgsUrlString= sellerExtendBean.getImgsUrl();
        String[] ImgsUrl=ImgsUrlString.split(",");
        for(int i=0;i<ImgsUrl.length;i++){
            SellerImgs sellerImgs=new SellerImgs();
            sellerImgs.setImg(ImgsUrl[i].toString());
            sellerImgs.setThumbnailImg(ImgsUrl[i].toString());
            sellerImgs.setSellerId(sellerID);
            sellerImgs.setOrd(i);
            sellerImgs.setUpdateTime(new Date());
            sellerImgs.setCreateTime(new Date());
            baseDao.save(sellerImgs);
        }
        flag=true;

        return flag;
    }
}
